package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.mapper.ApUserFanMapper;
import com.zhentao.mapper.ApUserFollowMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.user.dto.UserRelationDto;
import com.zhentao.model.user.pojo.ApUser;
import com.zhentao.model.user.pojo.ApUserFan;
import com.zhentao.model.user.pojo.ApUserFollow;
import com.zhentao.service.UserRelationService;
import com.zhentao.utils.common.AppUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserRelationServiceImpl implements UserRelationService {
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private RedisTemplate<String,String > redisTemplate;

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        ApUser user = AppUserThreadLocalUtil.getUser();
        if(user== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUserFollow apUserFollow=new ApUserFollow();
        ApUserFan apUserFan=new ApUserFan();
        if(dto.getOperation() == 0){
            apUserFollow.setUserId(user.getId());
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setFollowId(dto.getAuthorId());
            apUserFan.setUserId(dto.getAuthorId());
            apUserFan.setCreatedTime(new Date());
            apUserFan.setFansId(user.getId());
            apUserFanMapper.insert(apUserFan);
            apUserFollowMapper.insert(apUserFollow);
            redisTemplate.opsForHash().put("userFollow"+dto.getArticleId(),user.getId().toString(), JSON.toJSONString(dto));
        }else {
            LambdaQueryWrapper<ApUserFollow> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(ApUserFollow::getUserId, user.getId());
            wrapper.eq(ApUserFollow::getFollowId, dto.getAuthorId());
            apUserFollowMapper.delete(wrapper);
            LambdaQueryWrapper<ApUserFan> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUserFan::getFansId, user.getId());
            queryWrapper.eq(ApUserFan::getUserId, dto.getAuthorId());
            apUserFanMapper.delete(queryWrapper);
            redisTemplate.opsForHash().delete("userFollow"+dto.getArticleId().toString(),user.getId().toString());
        }
        return ResponseResult.okResult(200, "成功");
    }
}
